import { useUserStore } from '@/common/hox/userStore';
import { getAddress, getWxConfig } from '@/service';
import Taro, { useLaunch, useRouter } from '@tarojs/taro';
import { useRequest } from 'ahooks';
import { shareParam } from '@/utils';
import React from 'react';
import appConfig from '@/utils/appConfig';
import { PlatformEnum } from '@/utils/enum';
import { useInitStore } from '@/common/hox/initStore';
import { useAppSettingStore } from '@/common/hox/appSettingStore';
import request from '@/utils/request';

function HoxRootProvider(props: React.PropsWithChildren<any>) {
    const { initReady } = useInitStore();
    const { userInfo } = useUserStore();
    const { path, params } = useRouter();
    const { loginAsync, refreshUser } = useUserStore();
    useAppSettingStore();
    //  useNotifyTemplateStore()

    const getUrlParam = () => {
        const url = new URL(window.location.href);
        const { searchParams } = url;
        const urlParam = {
            // 第三方渠道用户唯一id
            uid: searchParams.get('uid'),
            // 时间戳
            timestamp: searchParams.get('timestamp'),
            // MD5签名
            sign: searchParams.get('sign'),
            // 福禄提供的唯一应用id
            aid: searchParams.get('aid'),
            // 推广员id
            sid: searchParams.get('sid'),
            // 客户端标识 1.h5 2.小程序
            ct: searchParams.get('ct') || '1',
            // 渠道 默认fulu
            channel: searchParams.get('channel') || '',
            // 扩展参数json
            ej: searchParams.get('ej'),
            // 经纬度
            lat: searchParams.get('lat') || '',
            lng: searchParams.get('lng') || '',
        };
        Taro.setStorageSync('open_url_param', urlParam);
        return urlParam;
    };

    const toErrorPage = () => {
        Taro.reLaunch({
            url: '',
        });
    };

    const OPEN_URL = [
        '/pages/index/index', // 首页
        '/pages/order/detail/index', // 订单详情
        '/pages/order/index', // 订单列表
    ];

    useLaunch((options: any) => {
        // 小程序新版本提示
        if (process.env.TARO_ENV === 'weapp') {
            const updateManager = Taro.getUpdateManager();
            updateManager.onUpdateReady(function () {
                Taro.showModal({
                    title: '版本更新提示',
                    content: '新版本已经准备好了，是否重启应用',
                    success: function (result) {
                        if (result.confirm) updateManager.applyUpdate();
                    },
                });
            });
        }

        // 初始化 进入页面存在值时 相关逻辑
        if (options.query) {
            const openUrlParam = Taro.getStorageSync('open_url_param');
            const shouldLogin = Boolean(
                (params.uid && params.aid) || (openUrlParam.uid && openUrlParam.aid)
            );
            // 用户进入目标路径 ，同时url或缓存中存在对应参数
            if (OPEN_URL.includes(path) && shouldLogin) {
                const token = Taro.getStorageSync('token');
                // 存在token 且当前缓存签名与 url携带签名一致 则不刷新token
                if (
                    token &&
                    params.sign &&
                    params.sign === JSON.stringify({ sign: openUrlParam.sign })
                )
                    return;
                const isThirdPartyLogin = params.uid && params.aid && params.sign;
                const loginParams = isThirdPartyLogin ? getUrlParam() : openUrlParam;
                const {
                    aid: appConfigId,
                    uid: openId,
                    channel: channelPeugeot,
                    timestamp,
                    sign,
                } = loginParams || {};
                request
                    .post('/api/EmbedH5/Login', {
                        appConfigId,
                        openId,
                        channelPeugeot,
                        sign,
                        timestamp,
                    })
                    .then(async (res) => {
                        if (res?.accessToken) {
                            Taro.setStorageSync('token', res.accessToken);
                            await loginAsync();
                            refreshUser();
                        } else {
                            toErrorPage();
                        }
                    });
            }
        }
    });

    // 微信公众号初始化
    useRequest(getWxConfig, {
        ready: Boolean(userInfo && appConfig.appPlatformType === PlatformEnum.WeChatPub),
        onSuccess: (res) => {
            wx.config({
                ...res,
                jsApiList: [
                    'getLocation',
                    'chooseWXPay',
                    'updateAppMessageShareData',
                    'updateTimelineShareData',
                    'openLocation',
                ],
                openTagList: ['wx-open-launch-weapp'],
            });
            wx.ready(function () {
                wx.updateTimelineShareData(shareParam);
                wx.updateAppMessageShareData(shareParam);
            });
            // }
        },
    });

    // 获取城市信息
    useRequest(getAddress, {
        ready: Boolean(initReady),
        onSuccess: () => {
            // getGlobalStore()?.setlist(res?.list)
        },
    });

    return props.children;
}

export default HoxRootProvider;
